<?php

namespace Aincrid\MySwoole;


class Config
{
    public $configDir = ROOT_DIR . '/config';

    protected static $configs = [];


    public function __construct()
    {
        $this->readConfigDir();
    }

    public function set(string $key, string $value)
    {
        if (!str_contains($key, '.')) {
            return;
        }
        $dirs = explode('.', $key);

        static::$configs = array_merge(static::$configs, static::_set($dirs, count($dirs) - 1, $value));
    }

    protected static function _set($dirs, $index, $value, array $config = []): array
    {
        if ($index < 0) {
            return $config;
        }

        $array = [];
        $array[$dirs[$index]] = $value;
        return static::_set($dirs, --$index, $array, $array);
    }

    public function get(string $key): string|array
    {
        if (empty($key)) {
            return self::$configs;
        }

        $dirs = explode('.', $key);

        return static::_get($dirs, 0, static::$configs);
    }


    protected static function _get($dirs, $index, $configs)
    {
        if ($index > count($dirs) - 1) {
            return $configs;
        }
        $configs = $configs[$dirs[$index]] ?? '';
        return static::_get($dirs, ++$index, $configs);
    }

    public function readConfigDir($path = '')
    {
        if (empty($path)) {
            $path = $this->configDir;
        }
        if ($dirResource = opendir($path)) {
            while ($fileName = readdir($dirResource)) {
                if ($fileName == '.' || $fileName == '..') {
                    continue;
                }

                $configKey = substr($fileName, 0, -4);
                self::$configs[$configKey] = require_once $path . '/' . $fileName;
            }
        }
    }
}